#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include "elog.h"
#include "UiManager/UiManager.h"
#include "BackEnd.h"
#include "coder/upper_communication_coder/upper_communication_coder.h"

/**
QML -> QObj class <- C++
**/
#include "NanoIO/VirtualIO/NanoVirtualIO.h"
#include "NanoIO/SerialPortIO/SerialPortIO.h"
static void io_test(void)
{
    NanoIO* io = new NanoVirtualIO("test io");

    io->open();
    *io<<"HelloWorld";

    delete io;

    auto serialList = SerialPortIO::getSerialPortInfoList();

    SerialPortIO* serialIO = new SerialPortIO(&(*serialList.begin()));
    serialIO->open();

    *serialIO<<"HelloWorld!\r\n";
    *serialIO<<"I`m NanoCAN.";

    delete serialIO;
}

#include "EventManger/EventManager.h"
#include <windows.h>
static void event_test()
{
    EventManager* eventManage = new EventManager("Test");
    eventManage->start();
    EventManager::emitEvent( "Test" , 2 );
    delete eventManage;
}

static void log_module_init(void)
{
    elog_init();

    elog_set_text_color_enabled(0);

    elog_set_fmt( ELOG_LVL_VERBOSE , ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME );
    elog_set_fmt( ELOG_LVL_DEBUG , ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME);
    elog_set_fmt( ELOG_LVL_INFO , ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME);
    elog_set_fmt( ELOG_LVL_WARN , ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME );
    elog_set_fmt( ELOG_LVL_ERROR , ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME );

    elog_start();
}

int main(int argc, char *argv[])
{
    log_module_init();

    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    //将UiManager(UI控制器实例)添加到ui引擎的上下文中，方便C++、QML混合编程
    engine.rootContext()->setContextProperty("UiManager",UiManager::getInstance());

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    BackEndStart();

    io_test();
    event_test();

    nano_decoder_opt_t opt;
    get_upper_communication_decoder_opt(&opt);

    return app.exec();
}
